const taskbook = require("./index");
const getFlag = require("./Flag");
const { ipcMain, shell } = require('electron');
const Store = require('./store.js');

function messageHandler() {
  ipcMain.handle('dialog:getTask', handleGetTask);
  ipcMain.handle('dialog:sendTaskMessage', (event, input, flag) => handleTaskMessage(input, flag));
  ipcMain.handle('dialog:getTimelineTask', handleGetTimelineTask);
  ipcMain.handle('dialog:setUserData', (event, key, value) => handleSetUserData(key, value));
  ipcMain.handle('dialog:getUserData', (event, key) => handleGetUserData(key));
  ipcMain.handle('dialog:openHref', (event, href) => handleOpenHref(href));
}

async function handleTaskMessage(input, flag) {
  const flags = getFlag(flag);
  taskbook(input, flags);
}

async function handleGetTask() {
  const flags = getFlag();
  return taskbook([], flags);
}

async function handleGetTimelineTask() {
  const flags = getFlag({ timeline: true });
  return taskbook([], flags);
}

const store = new Store({
  configName: 'settings',
  defaults: {
    isHideComplete: false
  }
});

function handleSetUserData(key, value) {
  store.set(key, value);
}

function handleGetUserData(key) {
  return store.get(key);
}

function handleOpenHref(href) {
  shell.openExternal(href);
}

module.exports = messageHandler;